package cn.song.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author SongRenShuo
 * @date 2024/03/05
 */
@Configuration
public class ThreadPoolConfig {

    @Bean(name = "asyncExecutor")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(15);
        // 队列容量
        executor.setQueueCapacity(20);
        // 线程名称前缀
        executor.setThreadNamePrefix("Async-Executor-");
        // 拒绝策略 当线程池和队列都满载时，任务将由调用线程（通常是主线程）执行，而不是直接抛出异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
